import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';
import { useAuthStore } from '../store/modules/auth';
import { buildRoutesFromMenus, registerDynamicChildren } from './dynamic';

const Login = () => import('../views/Login.vue');
const AppLayout = () => import('../layout/AppLayout.vue');
const Home = () => import('../views/Home.vue');

const routes: RouteRecordRaw[] = [
  { path: '/login', name: 'login', component: Login },
  {
    path: '/',
    name: 'root',
    component: AppLayout,
    children: [
      { path: '', name: 'home', component: Home, meta: { title: '首页' } },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.onError((err) => {
  // 捕获路由懒加载等动态导入错误，便于定位真实问题
  console.error('[router] navigation error:', err);
});

let bootstrapped = false;
let dynRoutesMounted = false;

router.beforeEach(async (to, from, next) => {
  void from;
  const auth = useAuthStore();

  // 未登录则强制跳转登录页
  if (!auth.isLoggedIn && to.path !== '/login') {
    return next({ path: '/login', replace: true });
  }
  // 已登录访问登录页则跳首页
  if (auth.isLoggedIn && to.path === '/login') {
    return next({ path: '/', replace: true });
  }

  if (auth.isLoggedIn && !auth.initialized && !bootstrapped) {
    bootstrapped = true;
    try {
      await auth.bootstrap();
      if (!dynRoutesMounted) {
        const dyn = buildRoutesFromMenus(auth.menus || []);
        registerDynamicChildren(router, 'root', dyn);
        dynRoutesMounted = true;
      }
    } catch {
      await auth.logout();
      return next({ path: '/login', replace: true });
    }
  }

  // 基于 meta.perms 的权限校验
  const needPerms = (to.meta as any)?.perms as string[] | undefined;
  if (needPerms && needPerms.length > 0) {
    const ok = auth.hasAllPerm(needPerms);
    if (!ok) return next(false);
  }
  next();
});

export default router;